import { _decorator, Component, Node, Prefab, instantiate, v3, Label, Vec2, UITransform, Vec3, tween, director, AudioSource, AudioClip } from 'cc';
import { HexagonJenga_grid } from './HexagonJenga_grid';
import { HexagonJenga_GridDi } from './HexagonJenga_GridDi';
import { HexagonJenga_GameData } from './Data/HexagonJenga_GameData';
import { HexagonJenga_GameStorage } from './Data/HexagonJenga_GameStorage';
import { SSS_Consts } from 'db://assets/Script/Data/SSS_Consts';
import UI from 'db://assets/Script/Manager/UI';
import HexagonJenga_WinPanel from './UI/HexagonJenga_WinPanel';
import HexagonJenga_LosePanel from './UI/HexagonJenga_LosePanel';
import HexagonJenga_GamePanel from './UI/HexagonJenga_GamePanel';
import { bdlMgr } from 'db://assets/Script/Manager/BundleManager_S';
import { SSS_AudioManager } from 'db://assets/Script/Manager/SSS_AudioManager';
const { ccclass, property } = _decorator;

export const HexagonJenga_EventName = {
    clickGridDi: "clickGridDi",
    TouchStart: "TouchStart",
    TouchMove: "TouchMove",
    TouchEnd: "TouchEnd",
}

@ccclass('HexagonJenga_main')
export class HexagonJenga_main extends Component {
    public static Instance: HexagonJenga_main;

    @property(Prefab)
    gridDiPrefab: Prefab = null;

    @property(Prefab)
    gridPrefab: Prefab = null;

    private layoutHor = 5;
    private layoutVer = 5;
    private layoutVerGap = 10;

    private tileList: Node[][] = [];
    private currentSelectDi: HexagonJenga_GridDi = null;
    private gridMap: Map<number, Node[]> = new Map();
    private curSortIndex: number = -1;

    private isCanDo: boolean = true;
    /** 分组索引，一直累加 */
    private layoutSortIndex = 0;
    /** 剩余组别  */
    private layoutGroupCount = 0;
    private scaleC: number = 1//0.7;

    onLoad() {
        HexagonJenga_main.Instance = this;

        HexagonJenga_GameStorage.initData();

        this.scheduleOnce(() => {
            HexagonJenga_GamePanel.Instance.ShowOn();
        }, 0.1);

        // eventMgt.on(EventName.clickGridDi, this.evtClickGridDi, this);
        // eventMgt.on(EventName.TouchStart, this.evtTouchStart, this);
        // eventMgt.on(EventName.TouchMove, this.evtTouchMove, this);
        // eventMgt.on(EventName.TouchEnd, this.evtTouchEnd, this);

        HexagonJenga_main.Instance.node.on(HexagonJenga_EventName.clickGridDi, this.evtClickGridDi, this);
        HexagonJenga_main.Instance.node.on(HexagonJenga_EventName.TouchStart, this.evtTouchStart, this);
        HexagonJenga_main.Instance.node.on(HexagonJenga_EventName.TouchMove, this.evtTouchMove, this);
        HexagonJenga_main.Instance.node.on(HexagonJenga_EventName.TouchEnd, this.evtTouchEnd, this);

        // audioManager.onInit(this.node.getChildByName("bg").getComponent(AudioSource), this.node.getChildByName("gridBase").getComponent(AudioSource));
        // audioManager.play("background", SoundType.Music, true)
    }

    start() {
        this.layoutGrid();
        this.layoutGridBase();
        this.node.getChildByName("tips").active = false;
        this.node.getChildByName("result").active = false;
        this.initData();
    }

    evtTouchStart(p: Vec2) {
        if (!this.isCanDo) return;
        let pos = this.node.getChildByName("grid").getComponent(UITransform).convertToNodeSpaceAR(v3(p.x, p.y, 1));
        let pos1 = this.node.getChildByName("gridBase").getComponent(UITransform).convertToNodeSpaceAR(v3(p.x, p.y, 1));
        this.curSortIndex = this.getCurrentSelectedGrid(pos1);
    }

    private moveGapPos = null;
    private originPos = null;
    evtTouchMove(p: Vec2) {
        if (!this.isCanDo) return;
        if (this.curSortIndex < 0) return;
        let gridParent = this.node.getChildByName("grid");
        let pos = gridParent.getComponent(UITransform).convertToNodeSpaceAR(v3(p.x, p.y, 1));
        let pos1 = this.node.getChildByName("gridBase").getComponent(UITransform).convertToNodeSpaceAR(v3(p.x, p.y, 1));
        // let curDi = this.getCurrentSelectDi(pos);
        let group = this.gridMap.get(this.curSortIndex);
        if (group) {
            if (!this.moveGapPos) {
                this.moveGapPos = pos1;
            }
            if (!this.originPos) {
                this.originPos = group[0].position
            }
            else {
                let newPos = v3(this.moveGapPos.x - pos1.x, this.moveGapPos.y - pos1.y);
                for (let i = 0; i < group.length; i++) {
                    let xx = group[i].position.x - newPos.x;
                    let yy = group[i].position.y - newPos.y;
                    group[i].setPosition(v3(xx, yy));
                    if (this.currentSelectDi) {
                        // group[i].parent = this.currentSelectDi.node;
                    }
                }
                // group.sort((a, b) => { return a.getComponent(gridCmpt).index - b.getComponent(gridCmpt).index });
                let pos2 = gridParent.getComponent(UITransform).convertToNodeSpaceAR(group[0].worldPosition);
                this.getCurrentSelectDi(pos2, true);
                this.moveGapPos = pos1;
                this.sortGridMap();
            }
        }
    }

    async evtTouchEnd(p: Vec2) {
        if (!this.isCanDo) return;
        if (this.currentSelectDi) {
            let gridParent = this.node.getChildByName("gridBase");
            let pos1 = gridParent.getComponent(UITransform).convertToNodeSpaceAR(this.currentSelectDi.node.worldPosition);
            let group = this.gridMap.get(this.curSortIndex);
            pos1 = v3();
            for (let i = 0; i < group.length; i++) {
                let xx = pos1.x;
                let yy = pos1.y + i * this.layoutVerGap;

                group[i].setPosition(v3(xx, yy));
                group[i].getComponent(HexagonJenga_grid).setHorVer(this.currentSelectDi.hor, this.currentSelectDi.ver);
                // group[i].setSiblingIndex(this.currentSelectDi.sibIndex + i);
                group[i].parent = this.currentSelectDi.node;

            }
            // audioManager.play("pop_up")
            this.currentSelectDi.showSelected(false);
            this.isCanDo = false;
            await this.startCheckMove().then(() => { }).catch();
        } else {
            let group = this.gridMap.get(this.curSortIndex);
            if (group) {
                group.forEach((item, idx) => {
                    let xx = -200 + (item.getComponent(HexagonJenga_grid).posIndex % 3) * 200;
                    let yy = item.getComponent(HexagonJenga_grid).index * this.layoutVerGap;
                    item.setPosition(v3(xx, yy));
                })
            }
            this.currentSelectDi = null;
            this.curSortIndex = -1;
            this.moveGapPos = null;
            this.originPos = null;
            this.sortGridMap();
        }
        this.checkDiIsGameOver();
    }

    async startCheckMove() {
        return new Promise(async resolve => {
            let bool = await this.checkAllNerby();
            if (bool) {
                this.startCheckMove();
            }
            else {
                this.currentSelectDi = null;
                this.curSortIndex = -1;
                this.moveGapPos = null;
                this.originPos = null;
                this.isCanDo = true;
                this.layoutGroupCount--;
                if (this.layoutGroupCount <= 0) {
                    this.layoutGridBase();
                }
                this.sortGridMap();
                resolve("");
            }
        });
    }

    async handleTest() {
        this.node.getChildByName("tips").active = true;
        this.node.getChildByName("tips").getChildByName("lb").active = true;
        this.node.getChildByName("tips").getChildByName("lb1").active = false;
        this.scheduleOnce(() => {
            this.node.getChildByName("tips").active = false;
        }, 1);
        this.nextLevel();
    }
    async handleTest1() {
        // this.lv--;
        // if (this.lv < 1) {
        //     this.lv = 1;
        // }
        // this.node.getChildByName("tips").active = true;
        // this.node.getChildByName("tips").getChildByName("lb").active = false;
        // this.node.getChildByName("tips").getChildByName("lb1").active = true;
        // this.scheduleOnce(() => {
        //     this.node.getChildByName("tips").active = false;
        // }, 1);
        // this.initData();
        this.clearData();
    }

    /** 开始移动 */
    async startMove(idx1: number, idx2: number) {
        return new Promise(async resolve => {
            let sortIndex1 = idx1;
            let sortIndex2 = idx2;
            let list1 = this.gridMap.get(sortIndex1);
            let list2 = this.gridMap.get(sortIndex2);
            let tPos = list2[list2.length - 1].position;
            // let tPos = this.node.getChildByName("grid").parent.getComponent(UITransform).convertToNodeSpaceAR(list2[list2.length - 1].worldPosition)
            let kind = list1[list1.length - 1].getComponent(HexagonJenga_grid).kind;
            /** 把list1 全部移动到 list2 */
            let len = 0;
            for (let i = list1.length - 1; i >= 0; i--) {
                if (list1[i].getComponent(HexagonJenga_grid).kind == kind) {
                    len++;
                } else {
                    break;
                }
            }
            let count = 0;
            let reFunc = () => {
                let lst = [];
                for (let i = 0; i < list1.length - len; i++) {
                    lst.push(list1[i]);
                }
                this.gridMap.set(sortIndex1, lst);
            }
            let item2 = list2[0].getComponent(HexagonJenga_grid);
            for (let i = list1.length - 1; i >= list1.length - len; i--) {
                await this.delayTime(0.05);
                let item = list1[i];
                let pp = item2.node.parent.getComponent(UITransform).convertToNodeSpaceAR(item.worldPosition);
                item.parent = item2.node.parent;
                item.setPosition(pp);
                let targetPos = v3(tPos.x, tPos.y + (list1.length - i) * this.layoutVerGap);
                let yy = targetPos.y > list1[0].position.y ? targetPos.y : list1[0].position.y;
                // let centerPos = v3((item.position.x + tPos.x) / 2, yy + 200)
                let centerPos = v3((pp.x + tPos.x) / 2, yy + 200)
                item.setSiblingIndex(99 - i);
                let time = 0.3;
                // audioManager.play("cardSounds")

                let audio_root = `audio/水音效2`;
                bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                    SSS_AudioManager.Instance.playSFX(res, false);
                });

                // console.log(`cardSounds------------1`);
                tween(item).parallel(
                    tween(item).to(time, { position: centerPos }),
                    tween(item).to(time, { scale: v3(this.scaleC, 0.1, 1) }),
                ).call(() => {
                    // audioManager.play("cardSounds")
                    let audio_root = `audio/水音效1`;
                    bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                        SSS_AudioManager.Instance.playSFX(res, false);
                    });
                    // console.log(`cardSounds------------2`);

                    item.setSiblingIndex(50);
                }).parallel(
                    tween(item).to(time, { position: targetPos }),
                    tween(item).to(time, { scale: v3(this.scaleC, this.scaleC, 1) }),
                ).call(async () => {
                    // audioManager.play("cardSounds")
                    // console.log(`cardSounds------------3`);

                    let audio_root = `audio/水音效1`;
                    bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                        SSS_AudioManager.Instance.playSFX(res, false);
                    });

                    item.getComponent(HexagonJenga_grid).setIdx(sortIndex2, list2.length)
                    item.getComponent(HexagonJenga_grid).setHorVer(item2.hor, item2.ver)
                    list2.push(item);
                    count++;
                    if (count == len) {
                        reFunc();
                        this.gridMap.set(sortIndex2, list2);
                        await this.checkElimilate(sortIndex2);
                        resolve("");
                    }
                }).start();
            }
        })
    }

    /** 消除检测，大于10就消除 */
    async checkElimilate(sortIndex: number) {
        return new Promise(async resolve => {
            let list = this.gridMap.get(sortIndex);
            let first = list[0].getComponent(HexagonJenga_grid).kind;
            let count = 0;
            for (let i = 0; i < list.length; i++) {
                if (list[i].getComponent(HexagonJenga_grid).kind == first) {
                    count++;
                }
            }
            if (count == list.length && count >= 10) {
                let count2 = 0;
                let kind = list[0].getComponent(HexagonJenga_grid).kind;
                for (let i = count - 1; i >= 0; i--) {
                    await this.delayTime(0.05);
                    tween(list[i]).to(0.1, { scale: v3() }).call(() => {
                        // audioManager.play("collect")

                        let audio_root = `audio/水音效1`;
                        bdlMgr.getRes<AudioClip>(SSS_Consts.BundleName.AUDIO, audio_root, AudioClip).then(res => {
                            SSS_AudioManager.Instance.playSFX(res, false);
                        });


                        count2++;
                        list[i].destroy();
                        if (count2 == count) {
                            this.gridMap.set(sortIndex, []);
                            this.handleLevelTarget(kind);
                            resolve("");
                        }
                    }).start();
                }
            }
            else {
                resolve("");
            }
        });
    }

    /** 检测整个网格的相邻情况 */
    async checkAllNerby() {
        return new Promise(async resolve => {
            let sortList: number[] = [];
            let len = this.layoutSortIndex + 1;//this.layoutHor * this.layoutVer;
            let nowSortIndex = -1;
            let nerbySortIndex = -1;
            for (let i = 0; i < len; i++) {
                nowSortIndex = i;
                let group = this.gridMap.get(i);
                if (!group) continue;
                sortList = this.getNerbSortListIndex(group);
                if (sortList.length > 0) {
                    /** 这里还要加判断，相邻连个组是否有可以合成的 */
                    nerbySortIndex = this.checkIsCanMerge(sortList, group);
                    if (nerbySortIndex >= 0) break;
                }
            }
            if (nowSortIndex < 0 || nerbySortIndex < 0) {
                resolve(false);
                return;
            }
            let list1 = this.gridMap.get(nowSortIndex);
            let list2 = this.gridMap.get(nerbySortIndex);
            let kind = list1[list1.length - 1].getComponent(HexagonJenga_grid).kind;
            let count1 = 0;
            let count2 = 0;
            for (let i = list1.length - 1; i >= 0; i--) {
                if (list1[i].getComponent(HexagonJenga_grid).kind == kind) {
                    count1++;
                }
                else {
                    break;
                }
            }
            for (let i = list2.length - 1; i >= 0; i--) {
                if (list2[i].getComponent(HexagonJenga_grid).kind == kind) {
                    count2++;
                }
                else {
                    break;
                }
            }
            if (count1 == list1.length) {
                await this.startMove(nerbySortIndex, nowSortIndex);
            }
            else if (count2 == list2.length) {
                await this.startMove(nowSortIndex, nerbySortIndex);
            }
            /** 少的往多的移动 */
            else if (count1 >= count2) {
                await this.startMove(nerbySortIndex, nowSortIndex);
            }
            else {
                await this.startMove(nowSortIndex, nerbySortIndex);
            }
            resolve(true);
        });
    }

    /** 是否可以合并 */
    checkIsCanMerge(sortList: number[], group: Node[]) {
        let kind1 = group[group.length - 1].getComponent(HexagonJenga_grid).kind;
        for (let j = 0; j < sortList.length; j++) {
            let nerbyList = this.gridMap.get(sortList[j]);
            if (sortList[j] >= 0 && nerbyList) {
                let kind2 = nerbyList[nerbyList.length - 1].getComponent(HexagonJenga_grid).kind;
                if (kind1 == kind2) {
                    return sortList[j];
                }
            }
        }
        return -1;
    }

    getNerbSortListIndex(group: Node[]) {
        let sortList: number[] = [];
        if (group && group.length > 0 && group[0].getComponent(HexagonJenga_grid).hor >= 0) {
            sortList = this.getNerbSortIndex(group[0].getComponent(HexagonJenga_grid).hor, group[0].getComponent(HexagonJenga_grid).ver);
            if (sortList.length > 0) {
                return sortList;
            }
        }
        return sortList;
    }

    checkDiIsEmpty(hor: number, ver: number) {
        let bool = false;
        this.gridMap.forEach((list: Node[], idx: number) => {
            if (list.length > 0) {
                let item = list[0].getComponent(HexagonJenga_grid);
                if (item.hor == hor && item.ver == ver) {
                    bool = true;
                    return bool;
                }
            }
        });
        return bool;
    }

    /** 结束检测 */
    checkDiIsGameOver() {
        let bool = true;
        let hor = this.layoutHor;
        let ver = this.layoutVer;
        for (let i = 0; i < hor; i++) {
            for (let j = 0; j < ver; j++) {
                let item = this.tileList[i][j];
                if (item) {
                    let scp = item.getComponent(HexagonJenga_GridDi);
                    if (!this.checkDiIsEmpty(scp.hor, scp.ver)) {
                        bool = false;
                        return bool;
                    }
                }
            }
        }
        if (bool) {
            this.showLoseView();
        }
        return bool;
    }

    /** 当前在哪一个底板上面 */
    getCurrentSelectDi(pos: Vec3, isShowCenter: boolean = false): HexagonJenga_GridDi {
        let hor = this.layoutHor;
        let ver = this.layoutVer;
        for (let i = 0; i < hor; i++) {
            for (let j = 0; j < ver; j++) {
                let item = this.tileList[i][j];
                if (item) {
                    let scp = item.getComponent(HexagonJenga_GridDi);
                    if (scp.isClickInside(pos) && !this.checkDiIsEmpty(scp.hor, scp.ver)) {
                        this.currentSelectDi = scp;
                        this.evtClickGridDi(scp.hor, scp.ver, isShowCenter);
                        return scp;
                    }
                }
            }
        }
        if (this.currentSelectDi) {
            this.currentSelectDi.showSelected(false);
            this.currentSelectDi = null;
        }
        return null;
    }

    /** 当前选中的分组，网格之外 */
    getCurrentSelectedGrid(pos: Vec3) {
        let sourtIndex: number = -1;
        this.gridMap.forEach((gridlist: Node[], index) => {
            for (let i = 0; i < gridlist.length; i++) {
                let item = gridlist[i].getComponent(HexagonJenga_grid);
                if (item.isClickInside(pos)) {
                    sourtIndex = item.sortIndex;
                    // audioManager.play("click")
                    return sourtIndex;
                }
            }
        });
        return sourtIndex;
    }

    layoutGridBase() {
        let list = [
            this.getOneGroup(),
            this.getOneGroup(),
            this.getOneGroup(),
        ]

        this.layoutGroupCount = 0;
        this.node.getChildByName("gridBase").removeAllChildren();

        let map: Map<number, Node[]> = new Map();
        for (let i = 0; i < list.length; i++) {
            let gap = list[i].length;;
            this.layoutGroupCount++;
            for (let j = 0; j < gap; j++) {
                let grid = instantiate(this.gridPrefab);
                grid.setScale(v3(this.scaleC, this.scaleC))
                grid.getComponent(HexagonJenga_grid).setIdx(this.layoutSortIndex, j, i);
                if (!map.get(this.layoutSortIndex)) {
                    map.set(this.layoutSortIndex, [grid]);
                }
                else {
                    map.get(this.layoutSortIndex).push(grid);
                }
                grid.getComponent(HexagonJenga_grid).setKind(list[i][j]);
                this.node.getChildByName("gridBase").addChild(grid);
            }
            this.gridMap.set(this.layoutSortIndex, map.get(this.layoutSortIndex))
            this.layoutSortIndex++;
        }
        map.forEach((list, index) => {
            list.forEach((item, idx) => {
                let xx = -200 + (index % 3) * 200;
                let yy = item.getComponent(HexagonJenga_grid).index * this.layoutVerGap;
                item.setPosition(v3(xx, yy))
            })
        });
    }

    sortGridMap() {
        this.gridMap.forEach((list, index) => {
            for (let i = list.length - 1; i >= 0; i--) {
                let hor = list[0].getComponent(HexagonJenga_grid).hor;
                let ver = list[0].getComponent(HexagonJenga_grid).ver;
                if (hor < 0) return;
                let sib = this.tileList[hor][ver].getComponent(HexagonJenga_GridDi).sibIndex;
                let item = list[i];
                let gap = sib + i;
                item.getComponent(HexagonJenga_grid).showSib(gap)
            }
        });
    }

    evtClickGridDi(hor, ver, isShowCenter) {
        this.tileList.forEach(citem => {
            citem.forEach(item => {
                // item.getChildByName("s").active = false;
                // item.getChildByName("c").active = false;
            })
        })
        if (isShowCenter) {
            this.showCurentDi(hor, ver);
        }
        else {
            this.showNerb(hor, ver);
        }
    }

    async delayTime(t: number) {
        return new Promise(resolve => {
            this.scheduleOnce(() => {
                resolve("");
            }, t);

            // setTimeout(() => {
            //     resolve("");
            // }, t * 1000);
        });

        // return new Promise(resolve => {
        //     setTimeout(() => {
        //         resolve("");
        //     }, t * 1000);
        // });
    }

    async layoutGrid() {
        let hor = this.layoutHor;
        let ver = this.layoutVer;
        let width = 110;
        let height = 122;
        let gap = 0;
        let count = 0;
        for (let i = 0; i < hor; i++) {
            this.tileList.push([]);
            for (let j = 0; j < ver; j++) {
                // await this.delayTime(0.001);
                let gridDi = this.getGridDi(count + "");
                // gridDi.getChildByName("s").active = false;
                // gridDi.getChildByName("c").active = false;
                gridDi.getComponent(HexagonJenga_GridDi).setInfo(i, j);
                this.tileList[i][j] = gridDi;
                count++;
                // gridDi.getChildByName("lb").getComponent(Label).string = sib + ""//`（${i}, ${j}）`;
            }
        }
    }

    clearData() {
        // eventMgt.off(EventName.clickGridDi, this);
        // eventMgt.off(EventName.TouchStart, this);
        // eventMgt.off(EventName.TouchMove, this);
        // eventMgt.off(EventName.TouchEnd, this);


        HexagonJenga_main.Instance.node.off(HexagonJenga_EventName.clickGridDi);
        HexagonJenga_main.Instance.node.off(HexagonJenga_EventName.TouchStart);
        HexagonJenga_main.Instance.node.off(HexagonJenga_EventName.TouchMove);
        HexagonJenga_main.Instance.node.off(HexagonJenga_EventName.TouchEnd);


        // director.loadScene("start");

        // let hor = this.layoutHor;
        // let ver = this.layoutVer;
        // for (let i = 0; i < hor; i++) {
        //     this.tileList.push([]);
        //     for (let j = 0; j < ver; j++) {
        //         this.tileList[i][j].removeAllChildren();
        //     }
        // }
        // this.layoutGridBase();
        // this.node.getChildByName("tips").active = false;
        // this.node.getChildByName("result").active = false;
        // this.currentSelectDi = null;
        // // this.gridMap.clear();
        // this.curSortIndex = -1;
        // this.initData();
    }

    showCurentDi(hor: number, ver: number) {
        let center = this.tileList[hor][ver];
        if (!center) return;
        // center.getChildByName("s").active = true;
    }

    /** 相邻底板查询，显示出来 */
    showNerb(hor: number, ver: number) {
        let center = this.tileList[hor][ver];
        if (!center) return;
        let gap = hor % 2;
        let top = (ver + 1 < this.layoutVer) && this.tileList[hor][ver + 1];
        let down = (ver - 1 >= 0) && this.tileList[hor][ver - 1];
        let leftUp = (ver + 1 < this.layoutVer && hor - 1 >= 0) && this.tileList[hor - 1][ver + 1];
        let leftDown = hor - 1 >= 0 && this.tileList[hor - 1][ver];
        if (gap == 0) {
            leftUp = (hor - 1 >= 0 && ver - 1 >= 0) && this.tileList[hor - 1][ver - 1];
            leftDown = hor - 1 >= 0 && this.tileList[hor - 1][ver];
        }
        let rightUp = (hor + 1 < this.layoutHor && ver + 1 < this.layoutVer) && this.tileList[hor + 1][ver + 1];
        let rightDown = hor + 1 < this.layoutHor && this.tileList[hor + 1][ver];
        if (gap == 0) {
            rightUp = hor + 1 < this.layoutHor && this.tileList[hor + 1][ver];
            rightDown = (hor + 1 < this.layoutHor && ver - 1 >= 0) && this.tileList[hor + 1][ver - 1];
        }

        this.showCurNerb(top);
        this.showCurNerb(down);
        this.showCurNerb(leftUp);
        this.showCurNerb(leftDown);
        this.showCurNerb(rightUp);
        this.showCurNerb(rightDown);
    }

    /** 获取相邻索引相邻 */
    getNerbSortIndex(hor: number, ver: number) {
        let list = [];
        let center = this.tileList[hor][ver];
        if (!center) return list;
        let gap = hor % 2;
        let top = (ver + 1 < this.layoutVer) && this.tileList[hor][ver + 1];
        let down = (ver - 1 >= 0) && this.tileList[hor][ver - 1];
        let leftUp = (ver + 1 < this.layoutVer && hor - 1 >= 0) && this.tileList[hor - 1][ver + 1];
        let leftDown = hor - 1 >= 0 && this.tileList[hor - 1][ver];
        if (gap == 0) {
            leftUp = (hor - 1 >= 0 && ver - 1 >= 0) && this.tileList[hor - 1][ver - 1];
            leftDown = hor - 1 >= 0 && this.tileList[hor - 1][ver];
        }
        let rightUp = (hor + 1 < this.layoutHor && ver + 1 < this.layoutVer) && this.tileList[hor + 1][ver + 1];
        let rightDown = hor + 1 < this.layoutHor && this.tileList[hor + 1][ver];
        if (gap == 0) {
            rightUp = hor + 1 < this.layoutHor && this.tileList[hor + 1][ver];
            rightDown = (hor + 1 < this.layoutHor && ver - 1 >= 0) && this.tileList[hor + 1][ver - 1];
        }

        let sourtIndex: number = -1;
        if (top) {
            sourtIndex = this.getNerbGridList(hor, ver + 1);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        if (down) {
            sourtIndex = this.getNerbGridList(hor, ver - 1);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        if (leftUp) {
            sourtIndex = this.getNerbGridList(leftUp.getComponent(HexagonJenga_GridDi).hor, leftUp.getComponent(HexagonJenga_GridDi).ver);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        if (leftDown) {
            sourtIndex = this.getNerbGridList(leftDown.getComponent(HexagonJenga_GridDi).hor, leftDown.getComponent(HexagonJenga_GridDi).ver);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        if (rightUp) {
            sourtIndex = this.getNerbGridList(rightUp.getComponent(HexagonJenga_GridDi).hor, rightUp.getComponent(HexagonJenga_GridDi).ver);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        if (rightDown) {
            sourtIndex = this.getNerbGridList(rightDown.getComponent(HexagonJenga_GridDi).hor, rightDown.getComponent(HexagonJenga_GridDi).ver);
            if (sourtIndex >= 0) {
                list.push(sourtIndex);
            }
        }
        return list;
    }

    /** 获取相邻分组 */
    getNerbGridList(hor: number, ver: number): number {
        let sourtIndex: number = -1;
        this.gridMap.forEach((gridlist: Node[], index) => {
            for (let i = 0; i < gridlist.length; i++) {
                let item = gridlist[i].getComponent(HexagonJenga_grid);
                if (item.hor == hor && item.ver == ver) {
                    sourtIndex = item.sortIndex;
                    return sourtIndex;
                }
            }
        });
        return sourtIndex;
    }

    showCurNerb(gridDi: Node) {
        if (!gridDi) return;
        // gridDi.getChildByName("s").active = true;
    }

    getGridDi(name: string) {
        if (!this.gridDiPrefab) return;
        let grid = instantiate(this.gridDiPrefab);
        // this.node.getChildByName("grid").getChildByName(name).addChild(grid);
        return this.node.getChildByName("grid").getChildByName(name);
        return grid;
    }



    /********************get group************************/
    private lv: number = 1;
    getOneGroup() {
        // let lv = this.lv;
        let lv = HexagonJenga_GameData.Get_level();
        let random = Math.floor(Math.random() * 5);
        let base = 4;
        let len = base + random;
        // let kinds = lv + 2 <= 8 ? lv + 2 : 8;\
        let kinds = this.getKinds();

        let kind = Math.ceil(Math.random() * kinds);
        let kind1 = Math.ceil(Math.random() * kinds);
        let resList: number[] = [];
        for (let i = 0; i < len; i++) {
            if (i < len / 2) {
                resList.push(kind1);
            } else {
                resList.push(kind);
            }
        }
        return resList;
    }

    private kinds: number = 3;
    getKinds() {
        if (this.lv < 4) {
            this.kinds = this.lv + 1;
        } else if (this.lv < 8) {
            this.kinds = 5;
        }
        else if (this.lv < 12) {
            this.kinds = 6;
        }
        else if (this.lv < 14) {
            this.kinds = 7;
        }
        else {
            this.kinds = 8;
        }
        // this.kinds = 8;
        return this.kinds;
    }

    initData() {
        this.lv = HexagonJenga_GameData.Get_level();

        this.targetMap.clear();
        this.setTargetInfo();
        this.updateTopInfo();
    }

    nextLevel() {
        HexagonJenga_GameData.Set_level(HexagonJenga_GameData.Get_level() + 1);

        this.lv = HexagonJenga_GameData.Get_level();


        this.node.getChildByName("result").active = false;
        // this.lv++;
        this.targetMap.clear();
        this.targetListMap.clear();
        this.setTargetInfo();
        this.updateTopInfo();

        director.loadScene(SSS_Consts.SceneName.HexagonJenga_Game_Scene);
    }

    private targetListMap: Map<number, number> = new Map();
    private targetMap: Map<number, number> = new Map();
    setTargetInfo() {
        this.getKinds();
        let len = this.kinds < 4 ? this.kinds : 3;
        let rand = Math.ceil(Math.random() * this.kinds);
        for (let i = 0; i < len; i++) {
            let idx = rand;
            let count = i + 1;
            this.targetListMap.set(idx, count);
            this.targetMap.set(idx, 0);
            rand++;
            if (rand > this.kinds) {
                rand = 1;
            }
        }
        // }
    }

    handleLevelTarget(kind: number) {
        let count = this.targetListMap.get(kind);
        if (count) {
            this.targetListMap.set(kind, --count);
            this.updateTopInfo();
        }
    }

    /** 更新顶部游戏信息 */
    updateTopInfo() {
        let top = this.node.getChildByName("top");
        let lbLevel = top.getChildByName("lbLevel");
        // CocosHelper.updateLabelText(lbLevel, `第${this.lv}关`);
        // CocosHelper.updateLabelText(lbLevel, `第${this.lv}关`);
        lbLevel.getComponent(Label).string = `第${this.lv}关`;

        let targetNode = top.getChildByName("targetNode");
        let isOver: boolean = true;
        targetNode.children.forEach(item => {
            item.active = false;
            if (this.targetListMap.get(+item.name)) {
                isOver = false;
                item.active = true;
                let lb = item.getChildByName("lb");
                let count = this.targetListMap.get(+item.name);
                // CocosHelper.updateLabelText(lb, count);
                lb.getComponent(Label).string = `${count}`;

            }
        })
        if (isOver) {
            this.showWin();
        }
    }

    /** 再次挑战 */
    challangeAgain() {
        this.node.getChildByName("result").active = false;
        this.clearData()
        director.loadScene(SSS_Consts.SceneName.HexagonJenga_Game_Scene);
    }

    showWin() {
        UI.Instance.CreatePanel_sub(`HexagonJenga_Prefab`, `UI/HexagonJenga_WinPanel`, HexagonJenga_WinPanel);

        // let result = this.node.getChildByName("result");
        // result.active = true;
        // result.getChildByName("win").active = true;
        // result.getChildByName("lose").active = false;
        // // audioManager.play("win");
    }

    showLoseView() {
        UI.Instance.CreatePanel_sub(`HexagonJenga_Prefab`, `UI/HexagonJenga_LosePanel`, HexagonJenga_LosePanel);

        // let result = this.node.getChildByName("result");
        // result.active = true;
        // result.getChildByName("lose").active = true;
        // result.getChildByName("win").active = false;
        // // audioManager.play("lose");
    }
}